import datetime
import hashlib
import logging
import os
import random
import time
import traceback
from datetime import datetime, timedelta
from itertools import groupby

import execjs
from toollib.guid import SnowFlake

import constants.Constants
from constants import Constants


def deleteFile(filePath):
    if os.path.exists(filePath):
        os.remove(filePath)


def groupByDataList(dataList, word):
    """
        根据对应字段将数据分组
    """
    if dataList is None and len(dataList) <= 0:
        return
    students_sorted = sorted(dataList, key=lambda x: x[word])
    resultList = []
    for key, grouper in groupby(students_sorted, key=lambda x: x[word]):
        lst = list(grouper)
        result = {
            'platform': key,
            'dataList': lst
        }
        resultList.append(result)
    return resultList


def splitList(needSplitList, size):
    """
    将一个列表切割成多个指定大小的子列表
    :param needSplitList: 原始列表
    :param size: 子列表大小
    :return: 切割后的子列表集合
    """
    return [needSplitList[i:i + size] for i in range(0, len(needSplitList), size)]


def get_sync_order_lanshou_values(dataList):
    """
        :param dataList:需要组装更新数据的数据列表
        :return 元素为元组的数据列表
    """
    aList = []
    for data in dataList:
        t = (
            data['statusCode'],
            data['statusStr'],
            data['logisticsInfo'],
            data['expressLastUpdateTime'],
            data['updateTime'],
            data['id'])
        aList.append(t)
    return aList


def get_sync_order_update_values(dataList):
    """
        :param dataList:需要组装更新数据的数据列表
        :return 元素为元组的数据列表
    """
    aList = []
    for data in dataList:
        t = (
            data['statusCode'],
            data['statusStr'],
            data['expressLastUpdateTime'],
            data['logisticsInfo'],
            data['updateTime'],
            data['id'])
        aList.append(t)
    return aList


def get_sync_order_yuyue_values(dataList):
    """
        :param dataList:需要组装更新数据的数据列表
        :return 元素为元组的数据列表
    """
    aList = []
    for data in dataList:
        t = (
            data['statusCode'],
            data['statusStr'],
            data['logisticsInfo'],
            data['updateTime'],
            data['id'])
        aList.append(t)
    return aList


def get_sync_order_tihuo_values(dataList):
    """
        :param dataList:需要组装更新数据的数据列表
        :return 元素为元组的数据列表
    """
    aList = []
    for data in dataList:
        t = (
            data['statusCode'],
            data['statusStr'],
            data['logisticsInfo'],
            data['updateTime'],
            data['id'])
        aList.append(t)
    return aList


def get_sync_order_sign_values(dataList):
    """
        :param dataList:需要组装更新数据的数据列表
        :return 元素为元组的数据列表
    """
    aList = []
    for data in dataList:
        t = (
            data['statusCode'],
            data['statusStr'],
            data['logisticsInfo'],
            data['expressLastUpdateTime'],
            data['updateTime'],
            data['id'])
        aList.append(t)
    return aList


def replaceEmojiByFenJi(twoPart):
    """
    将数字替换成emoji
    @param isVir:是否虚拟号码
    @param twoPart:
    @return:
    """
    try:
        if "1" in twoPart:
            twoPart = twoPart.replace("1", "⒈")
        if "2" in twoPart:
            twoPart = twoPart.replace("2", "⒉")
        if "3" in twoPart:
            twoPart = twoPart.replace("3", "⒊")
        if "4" in twoPart:
            twoPart = twoPart.replace("4", "⒋")
        if "5" in twoPart:
            twoPart = twoPart.replace("5", "⒌")
        if "6" in twoPart:
            twoPart = twoPart.replace("6", "⒍")
        if "7" in twoPart:
            twoPart = twoPart.replace("7", "⒎")
        if "8" in twoPart:
            twoPart = twoPart.replace("8", "⒏")
        if "9" in twoPart:
            twoPart = twoPart.replace("9", "⒐")
        return twoPart
    except Exception as ex:
        logging.info(f"emoji 替换异常:{str(ex)}")
        return twoPart


def getHandleExpressCode(rawMailNo, isLastCode):
    """
    获取处理过的物流单号
    :param isLastCode: 是否是尾号，如果不是尾号则替换成emoji
    :param rawMailNo: 上家单号
    :return: 处理过的单号
    """
    if not rawMailNo:
        return None
    if isLastCode is True:
        newMailNo = rawMailNo[-8:]
        return newMailNo
    else:
        newMailNo = replaceEmojiByFenJi(rawMailNo)
        return newMailNo


def getLocalNeedUpdateValues(dataList):
    """
        获取本地需要更新的数据库值
        :param dataList:需要组装更新数据的数据列表
        :return 元素为元组的数据列表
    """
    aList = []
    for data in dataList:
        t = (
            data['express'],
            data['updateTime'],
            data['is_deleted'],
            data['hasChangedExpressCode'],
            data['expressLastUpdateTime'],
            data['expressStatusStr'],
            data['expressStatusCode'],
            data['wuliuLongStr'],
            data['id'])
        aList.append(t)
    return aList


def getMd5EncryptContent(en_str):
    md5 = hashlib.md5()  # md5对象，md5不能反解，但是加密是固定的
    md5.update(en_str.encode('utf-8'))  # 要对哪个字符串进行加密，就放这里
    value = md5.hexdigest()
    return value


def gen_signature(url, ua, cookie):
    try:
        current_path = os.path.dirname(__file__)
        file = open(current_path + "/js/pdd20231025.js", mode="r")
        js = file.read()
        cxt = execjs.compile(js)
        signature = cxt.call("getAntiContent", url, ua, cookie)
        return signature
    except Exception as ex:
        logging.error("gen_signature Exception:%s", ex)
        logging.error("traceback.format_exc():\n%s" % traceback.format_exc())
        return None
    finally:
        file.close()

    # 调用快递100接口识别快递公司编号


def getContactPhone(contactPhone):
    if "-" in contactPhone:
        phoneAar = contactPhone.split("-")
        return phoneAar[0]
    return contactPhone


# 根据ID去重，重复时选择时间戳较大的那一个
def quChong(dataList):
    id_timestamp_map = {}
    for obj in dataList:
        if obj['id'] not in id_timestamp_map or obj['addTime'] > id_timestamp_map[obj['id']]['addTime']:
            id_timestamp_map[obj['id']] = obj

    # 获取去重后的对象列表
    unique_data = list(id_timestamp_map.values())
    return unique_data


def giftOrderIdQuChong(dataList):
    # 使用字典按照id进行分组，保留时间戳较大的对象
    id_timestamp_map = {}
    for obj in dataList:
        if obj['id'] not in id_timestamp_map or obj['addTime'] > id_timestamp_map[obj['id']]['addTime']:
            id_timestamp_map[obj['id']] = obj

    # 获取去重后的对象列表
    unique_data = list(id_timestamp_map.values())
    return unique_data


# 根据ID去重，重复时选择时间戳较大的那一个
def quChongLocal(dataList):
    # 使用字典按照id进行分组，保留时间戳较大的对象
    id_timestamp_map = {}
    for obj in dataList:
        if obj['id'] not in id_timestamp_map or obj['addTime'] > id_timestamp_map[obj['id']]['addTime']:
            id_timestamp_map[obj['id']] = obj

    # 获取去重后的对象列表
    unique_data = list(id_timestamp_map.values())
    return unique_data


# 获取下一站城市信息


def getNextCityInfo(strContent):
    findIndex = strContent.find("发往")
    newStr = strContent[findIndex + 2:]
    findIndex4 = newStr.find(",")
    findIndex5 = newStr.find("，")
    if findIndex5 > findIndex4:
        newStr = newStr[:findIndex4]
    elif findIndex5 < findIndex4:
        newStr = newStr[:findIndex5]
    findIndex2 = newStr.find("【")
    if findIndex2 == -1:
        return newStr.strip()
    else:
        findIndex3 = newStr.find("】")
        return newStr[findIndex2 + 1:findIndex3].strip()


def getRealContext(rawContext):
    # logisticsStrList = ['中通', '圆通', '韵达', '中国邮政', '申通', '百世汇通', '百世快递']
    if len(rawContext) > 130:
        rawContext = rawContext[0:126]
        findIndex = rawContext.rfind(',')
        findIndex2 = rawContext.rfind('，')
        if findIndex > findIndex2:
            rawContext = rawContext[0:findIndex] + "。"
        elif findIndex < findIndex2:
            rawContext = rawContext[0:findIndex2] + "。"
    # if '已转' in rawContext:
    #     return rawContext
    # for lo in logisticsStrList:
    #     if lo in rawContext:
    #         rawContext = rawContext.replace(lo, '融阅')
    #         break
    return rawContext


def getReceiverName(rawName):
    if rawName is None or len(rawName) <= 0:
        return "张宇辉"
    if "(" in rawName:
        findedIndex = rawName.find("(")
        rawName = rawName[0:findedIndex]
    if "（" in rawName:
        findedIndex = rawName.find("（")
        rawName = rawName[0:findedIndex]
    if len(rawName) > 12:
        return rawName[0:5]
    else:
        return rawName


def checkIsAutoSigned(currentTimetampStr):
    try:
        format_str = "%Y-%m-%d %H:%M:%S"
        dt = datetime.strptime(currentTimetampStr, format_str)
        new_dt = dt - timedelta(seconds=100)
        # 将13位时间戳转换为datetime对象
        dt1 = datetime.fromtimestamp(int(time.time()))
        dt2 = datetime.fromtimestamp(new_dt.timestamp())
        timedeltat = dt1 - dt2
        hours = int(timedeltat.total_seconds() / 3600)
        if hours > 100000:
            return True
        else:
            return False
    except Exception as ex:
        logging.error(f"checkIsAutoSigned:{str(ex)}")
        return False


# 获取格式化后的时间
def getFormatTime():
    now = datetime.now()
    time_str = now.strftime("%Y-%m-%d %H:%M:%S")
    return time_str


# 获取拼接取件码后的物流描述
def getAddedPickingCodeContext(express, mailNo, oldContext, pickingCode):
    try:
        dIndex = oldContext.find("，")
        if dIndex == -1:
            dIndex = oldContext.find(",")
        # newMailNo = mailNo[-8:]
        # addContent = f"已交[{express}]，单号尾号为：[{newMailNo}]"
        # oldContext = oldContext[:dIndex + 1] + addContent + oldContext[dIndex:]
        newContext = f"待取件，取件码:[{pickingCode}]," + oldContext[dIndex:]
        return newContext
    except Exception as ex:
        logging.error(f"添加取件码信息异常：{str(ex)}")


def getChangeCodeTime(timeStr):
    format_str = "%Y-%m-%d %H:%M:%S"
    dt = datetime.strptime(timeStr, format_str)
    new_dt = dt - timedelta(seconds=1)
    timestamp = int(new_dt.timestamp())
    new_time_str = datetime.fromtimestamp(timestamp).strftime(format_str)
    return new_time_str


# 获取当前城市
def getCurrentCity(areaName, location, context, receiverAddressCity):
    try:
        if not areaName and not location:
            return receiverAddressCity
        if not location:
            location = areaName
        if location is not None and len(location) > 18:
            return receiverAddressCity
        if "," in location:
            locationAar = location.split(",")
            endStr = locationAar[len(locationAar) - 1]
            if "区" in endStr:
                endStr = locationAar[len(locationAar) - 2]
            if len(locationAar) >= 2:
                return locationAar[1]
            else:
                # 只有一个
                first_part = locationAar[0]
                if first_part in receiverAddressCity or receiverAddressCity in first_part:
                    return receiverAddressCity
                else:
                    return endStr
        elif "，" in location:
            locationAar = location.split("，")
            endStr = locationAar[len(locationAar) - 1]
            if "区" in endStr:
                endStr = locationAar[len(locationAar) - 2]
            if len(locationAar) >= 2:
                return locationAar[1]
            else:
                # 只有一个
                first_part = locationAar[0]
                if first_part in receiverAddressCity or receiverAddressCity in first_part:
                    return receiverAddressCity
                else:
                    return endStr
        elif ' ' in location:
            arr = location.split(" ")
            endStr = arr[len(arr) - 1]
            if "区" in endStr:
                endStr = arr[len(arr) - 2]
            if len(arr) >= 2:
                return arr[1]
            else:
                # 只有一个
                first_part = arr[0]
                if first_part in receiverAddressCity or receiverAddressCity in first_part:
                    return receiverAddressCity
                else:
                    return endStr
        else:
            return receiverAddressCity
    except Exception as ex:
        logging.info(f"getCurrentCity error:areaName={areaName},location={location},context={context},ex={str(ex)}")


def get_city_by_context(context: str):
    """
    根据context 获取当前城市
    :param context:
    :return:
    """
    target_content = None
    if "【" in context:
        index_1 = context.find("【")
        index_2 = context.find("】")
        sub_content = context[index_1 + 1:index_2]
        if "市" in sub_content:
            target_content = sub_content
    return target_content


def get_logistics_current_address(areaName, location, context, re_City):
    """
    获取快递当前所在的地方，城市、区县
    :param areaName: 快递100字段areaName：陕西,汉中市,镇巴县
    :param location:快递100字段location：汉中市
    :param context: 物流描述
    :param re_City:收件城市
    :return:
    """
    try:
        is_area = False
        if not areaName and not location:
            if not context:
                return is_area, re_City
            city = get_city_by_context(context)
            if not city:
                return is_area, re_City
            return is_area, city

        result = None
        if areaName is not None:
            if "," in areaName:
                area_arr = areaName.split(",")
                area_end_str = area_arr[len(area_arr) - 1]
                if "区" in area_end_str or "县" in area_end_str:
                    is_area = True
                    result = area_arr[len(area_arr) - 1]
            elif "，" in areaName:
                area_arr = areaName.split("，")
                area_end_str = area_arr[len(area_arr) - 1]
                if "区" in area_end_str or "县" in area_end_str:
                    is_area = True
                    result = area_arr[len(area_arr) - 1]
        if result is None and location is not None:
            if "," in location:
                location_arr = location.split(",")
                location_end_str = location_arr[len(location_arr) - 1]
                if "区" in location_end_str or "县" in location_end_str:
                    is_area = True
                    result = location_end_str[len(location_end_str) - 1]
            elif "，" in location:
                location_arr = location.split("，")
                location_end_str = location_arr[len(location_arr) - 1]
                if "区" in location_end_str or "县" in location_end_str:
                    is_area = True
                    result = location_arr[len(location_arr) - 1]
        if result is None:
            if areaName is not None:
                if "," in areaName:
                    area_arr2 = areaName.split(",")
                    area_end_str2 = area_arr2[len(area_arr2) - 1]
                    if "区" not in area_end_str2 and "县" not in area_end_str2:
                        if len(area_end_str2) < 3:
                            result = area_end_str2
                        else:
                            result = area_arr2[len(area_arr2) - 2]
                elif "，" in areaName:
                    area_arr2 = areaName.split("，")
                    area_end_str2 = area_arr2[len(area_arr2) - 1]
                    if "区" not in area_end_str2 and "县" not in area_end_str2:
                        if len(area_end_str2) < 3:
                            result = area_end_str2
                        else:
                            result = area_arr2[len(area_arr2) - 2]
                else:
                    if "代收点" in areaName:
                        result = re_City
            elif location is not None:
                if "," in location:
                    location_arr2 = location.split(",")
                    location_end_str2 = location_arr2[len(location_arr2) - 1]
                    if "区" not in location_end_str2 and "县" not in location_end_str2:
                        if len(location_end_str2) < 3:
                            result = location_end_str2
                        else:
                            result = location_arr2[len(location_arr2) - 2]
                elif "，" in location:
                    location_arr2 = location.split("，")
                    location_end_str2 = location_arr2[len(location_arr2) - 1]
                    if "区" not in location_end_str2 and "县" not in location_end_str2:
                        if len(location_end_str2) < 3:
                            result = location_end_str2
                        else:
                            result = location_arr2[len(location_arr2) - 2]
                else:
                    if "代收点" in location:
                        result = re_City
        if not result:
            if areaName is not None:
                result = areaName
            elif location is not None:
                result = location
            else:
                result = re_City
        if "T" in result:
            result = result.replace("T", '')
        return is_area, result
    except Exception as ex:
        logging.info(f"get_logistics_current_address error:areaName={areaName},location={location},re_City={re_City},,context={context},ex={str(ex)}")


def getLocalCurrentCity(areaName, location, routeInfo):
    try:
        if not areaName and not location and not routeInfo:
            return '长沙市'
        if not location:
            location = areaName
        if location is not None and len(location) > 18:
            return location[0:5]
        if location is not None and len(location) > 0:
            if "," in location:
                locationAar = location.split(",")
                endStr = locationAar[len(locationAar) - 1]
                if "区" in endStr:
                    endStr = locationAar[len(locationAar) - 2]
                if not endStr:
                    return location
                return endStr
            elif "，" in location:
                locationAar = location.split("，")
                endStr = locationAar[len(locationAar) - 1]
                if "区" in endStr:
                    endStr = locationAar[len(locationAar) - 2]
                return endStr
            elif ' ' in location:
                arr = location.split(" ")
                endStr = arr[len(arr) - 1]
                if "区" in endStr:
                    endStr = arr[len(arr) - 2]
                if not endStr:
                    return location
                return endStr
            else:
                return location
        else:
            if not routeInfo:
                return location
            if "," in routeInfo:
                locationAar = routeInfo.split(",")
                endStr = locationAar[len(locationAar) - 1]
                if "区" in endStr:
                    endStr = locationAar[len(locationAar) - 2]
                if not endStr:
                    return location
                return endStr
            elif "，" in routeInfo:
                locationAar = routeInfo.split("，")
                endStr = locationAar[len(locationAar) - 1]
                if "区" in endStr:
                    endStr = locationAar[len(locationAar) - 2]
                return endStr
            elif ' ' in routeInfo:
                arr = routeInfo.split(" ")
                endStr = arr[len(arr) - 1]
                if "区" in endStr:
                    endStr = arr[len(arr) - 2]
                if not endStr:
                    return location
                return endStr
            else:
                return routeInfo
    except Exception as ex:
        logging.info(
            f"getLocalCurrentCity error:areaName={areaName},location={location},routeInfo={routeInfo},ex={str(ex)}")


def getFacilityNo(areaCode):
    if areaCode is None or len(str(areaCode)) <= 0:
        areaCode = str(int(time.time() * 1000))[6:]
    return areaCode


def getFacilityName(strContent):
    returnStr = '代收点'
    if "代收点" in strContent:
        returnStr = '代收点'
    index1 = strContent.find("来【")
    if index1 != -1:
        strContent2 = strContent[index1 + 2:]
        index2 = strContent2.find("】")
        strContent3 = strContent2[:index2]
        returnStr = strContent3
    elif strContent.find("的【") != -1:
        index3 = strContent.find("的【")
        strContent3 = strContent[index3 + 2:]
        index4 = strContent3.find("】")
        strContent4 = strContent3[:index4]
        returnStr = strContent4
    else:
        if "签收人" in strContent:
            i1 = strContent.find("签收人")
            returnStr = strContent[i1 + 4: i1 + 7]
        elif "离开【" in strContent:
            index7 = strContent.find("【")
            index8 = strContent.find("】")
            if index7 != -1 and index8 != -1 and index8 > index7:
                s = strContent[index7 + 1:index8]
                returnStr = s
        else:
            index5 = strContent.rfind("【")
            index6 = strContent.rfind("】")
            if index5 == -1 or index6 == -1:
                returnStr = '代收点'
            else:
                s = strContent[index5 + 1:index6]
                sIndex = s.find("：")
                if sIndex != -1:
                    returnStr = s.split("：")[1]
                sIndex2 = s.find(":")
                if sIndex2 != -1:
                    returnStr = s.split(":")[1]
                else:
                    returnStr = s
    if not returnStr or len(returnStr) > 10:
        return '代收点'
    return returnStr


def getSaveAddressParam(dbItem):
    try:
        param = {
            "id": SnowFlake().gen_uid(),
            "receiverAddressProvince": dbItem.get("receiverAddressProvince"),
            "receiverAddressCity": dbItem.get('receiverAddressCity'),
            "receiverAddressRegion": dbItem.get('receiverAddressRegion'),
            "receiverAddressDetail": dbItem.get('receiverAddressDetail'),
            "mailNo": dbItem.get('mailNo'),
            "createTime": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        return param
    except Exception as ex:
        logging.error("getSaveAddressParam Exception:%s", ex)
        logging.error("traceback.format_exc():\n%s" % traceback.format_exc())


def getLastUpdateTimeIndex(existTime, lotisticsList):
    findIndex = -1
    if not existTime or not lotisticsList:
        return findIndex
    for index, item in enumerate(lotisticsList):
        timeStr = item['time']
        if timeStr == existTime:
            findIndex = index
            break
    return findIndex


def getLogisticsFirstYunshuItem(lotisticsList, statusList):
    reList = reversed(lotisticsList)
    for item in reList:
        statusCode = item['statusCode']
        if statusCode in statusList:
            return item


def getLastIndexByLastUpdateTime(logisticsList, lastUpdateTime):
    """
    根据上一次的更新时间获取它在物流中的位置
    :param logisticsList:
    :param lastUpdateTime:
    :return:
    """
    if not logisticsList or not lastUpdateTime:
        return -1
    for index, item in enumerate(logisticsList):
        timeStr = item['time']
        if timeStr == lastUpdateTime:
            return index
    return -1


def computeNowAndParamTimeHour(lastTime, nextTime):
    """
    计算时间
    :param paramTime:
    :return:
    """
    try:
        time1 = datetime.strptime(lastTime, "%Y-%m-%d %H:%M:%S")
        time2 = datetime.strptime(nextTime, "%Y-%m-%d %H:%M:%S")
        # 计算时间差
        time_diff = time2 - time1
        # 提取出小时数
        hours = int(time_diff.total_seconds() / 3600)
        return hours
    except Exception as ex:
        logging.error(f"计算小时数异常：Exception-->" + str(ex))
        logging.error("揽收异常2:%s", traceback.format_exc())
        return 0


def jisuanShiJianTianShuJianGe(startTime):
    """
    计算时间天数间隔
    :param startTime:
    :return:
    """
    # 将传入的时间字符串转换为 datetime 对象
    target_date = datetime.strptime(startTime, '%Y-%m-%d %H:%M:%S')

    # 获取当前时间
    current_date = datetime.now()

    # 计算日期差
    date_difference = current_date - target_date

    # 提取天数部分
    days_difference = date_difference.days

    return days_difference


def getCurrentHour():
    # 获取当前时间
    current_time = datetime.now()

    # 提取当前小时数
    current_hour = current_time.hour

    return current_hour


def get_day_before_days(before_day):
    """
    获取指定天数之前的时间
    :param before_day:指定的天数
    :return:
    """
    today = datetime.today()
    one_month_ago = today - timedelta(days=before_day)
    need_time = one_month_ago.strftime("%Y-%m-%d")
    return need_time


def get_sub_time(logistics_update_time, jg_time):
    """
    判断是否超过间隔时间
    logistics_update_time：物流更新时间
    jg_time：间隔时间，单位小时
    """
    date_format = "%Y-%m-%d %H:%M:%S"
    l_u_time = datetime.strptime(logistics_update_time, date_format)
    current_time = datetime.now()
    time_diff = current_time - l_u_time
    return time_diff >= timedelta(hours=jg_time)


def get_province_name(start_full_name: str):
    """
    获取省份
    :param start_full_name:
    :return:
    """
    try:
        if "," in start_full_name:
            return start_full_name.split(",")[0]
        elif "，" in start_full_name:
            return start_full_name.split("，")[0]
        else:
            if start_full_name in ['北京', '天津', '重庆', '上海']:
                return start_full_name
            return None
    except Exception as ex:
        logging.error(f"获取出发地省份异常，参数：{start_full_name},异常：{str(ex)}")


def get_province_by_city(city_name):
    for item in constants.Constants.address_list:
        city_list = item.get("city_list")
        for city in city_list:
            if city in city_name or city_name in city:
                return item['name']


def get_current_address(areaName, location):
    """
    根据快递100里面的数据获取快递当前位置
    :param areaName:
    :param location:
    :return:
    """
    if not areaName and not location:
        return None
    if areaName is not None:
        p_name = get_province_name(areaName)
        return p_name
    if location is not None:
        l_arr = []
        if "," in location:
            l_arr = location.split(",")
        elif "，" in location:
            l_arr = location.split("，")
        else:
            if "T" in location:
                current_province = get_province_by_city(location.replace("T", ""))
                return current_province
        if not l_arr:
            return None
        first_part = l_arr[0]
        if "省" in first_part:
            return first_part
        elif "市" in first_part:
            return get_province_by_city(first_part)
        elif "自治州" in first_part or "自治县" in first_part or "自治区" in first_part:
            return get_province_by_city(first_part)
    return None


def get_current_timetamp():
    return int(time.time() * 1000)


def get_encrypt_pwd(raw_pwd):
    temp_pwd = f"Alq_{raw_pwd}&%56"
    pwd = hashlib.md5(temp_pwd.encode(encoding='UTF-8')).hexdigest().upper()
    return pwd


def get_current_format_time():
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return current_time


def filter_text_by_array(original_text):
    """
    根据过滤数组移除原始文本中的匹配内容

    Args:
        original_text (str): 原始文本内容
        filter_arr (list): 需要过滤的字符串数组

    Returns:
        str: 处理后的文本（未匹配时返回原文本）
    """
    filter_arr = Constants.filter_arr
    if not isinstance(original_text, str) or not isinstance(filter_arr, list):
        return original_text
    try:
        for word in filter_arr:
            if word in original_text:
                original_text = original_text.replace(word, '')
        return original_text
    except Exception:
        return original_text


import re


def is_have_keywords(text):
    keywords = ["妈妈驿站", "菜鸟驿站", "驿站", "代收", "暂存", "保管", "取件", "自提", "如有取件码问题"]
    pattern = re.compile('|'.join(re.escape(word) for word in keywords))
    return bool(pattern.search(text))


if __name__ == '__main__':
    # print(get_sub_time("2025-04-21 12:51:08"))
    # print(get_day_before_days(10))
    #
    # area_name = None
    # location = "大理白族自治州,大理市"
    # context = ""
    # re_City = "北京市"
    # # print(get_logistics_current_address(area_name, location, context, re_City))
    #
    # print(get_current_address(area_name, location))

    text1 = "【自提柜】包裹已签收！如有问题请联系派件员：15216543205，您的快递已经妥投，投诉电话：05392490090。有事呼叫我，勿找平台，少一次投诉，多一份感恩。"
    print(filter_text_by_array(text1))
    text2 = "【自提柜】您的包裹已存放至【心甜智能柜】，取件地址【朝阳佳苑3号楼下】，如有取件码问题或找不到包裹等问题，请联系：快递员【18763765477】，投诉电话【05392490090】"
    print(filter_text_by_array(text2))
    text2 = "【临沂市】山东沂南县公司 的快递员(戚桂富/18763765477)正在为您派送(有事呼叫我，勿找平台，少一次投诉，多一份感恩)，投诉电话：05392490090，可放心接听95089申通专属派送号码"
    print(filter_text_by_array(text2))
